import Cookie from 'js-cookie'

export function formatTime(date, fmt) {
  var o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(), //日
    'h+': date.getHours(), //小时
    'm+': date.getMinutes(), //分
    's+': date.getSeconds(), //秒
    'q+': Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds() //毫秒
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
  return fmt
}

export function checkPhone(phone) {
  if (!/^1[123456789]\d{9}$/.test(phone)) return false
  else return true
}

export function dayOfWeek(date) {
  return '日一二三四五六'.split('')[date.getDay()]
}

export function dealDate(year, month, day) {
  if (day < 10) day = '0' + day
  if (month < 10) month = '0' + month
  return year + '-' + month + '-' + day
}

export function buling(num) {
  if (num < 10) num = '0' + num
  return num
}

// 判断PC或者mobile
export const pcOrMobile = navigator => {
  if (
    navigator.match(/Android/i) ||
    navigator.match(/webOS/i) ||
    navigator.match(/iPhone/i) ||
    navigator.match(/iPad/i) ||
    navigator.match(/iPod/i) ||
    navigator.match(/BlackBerry/i) ||
    navigator.match(/Windows Phone/i)
  ) {
    return 'mobile'
  } else {
    return 'pc'
  }
}

//获取服务端cookie
export function getCookiesInServer(req) {
  let service_cookie = {}
  req &&
  req.headers.cookie &&
  req.headers.cookie.split(';').forEach(function(val) {
    let parts = val.split('=')
    service_cookie[parts[0].trim()] = (parts[1] || '').trim()
  })
  return service_cookie
}
//获取客户端cookie
export function getCookiesInClient(key) {
  return Cookie.get(key) ? Cookie.get(key) : ''
}
